import React, { useState } from 'react'
import {
  Card,
  Space,
  Button,
  Typography,
  Tag,
  Tooltip,
  Descriptions,
  Divider,
  Modal,
  Input,
  message,
} from 'antd'
import {
  EyeOutlined,
  EditOutlined,
  CopyOutlined,
  RollbackOutlined,
  DeleteOutlined,
  DownloadOutlined,
  TagOutlined,
  UserOutlined,
  ClockCircleOutlined,
  FileTextOutlined,
} from '@ant-design/icons'
import MonacoSQLEditor from '@/components/Editor/MonacoSQLEditor'
import { formatDateTime, formatFileSize, copyToClipboard, downloadFile } from '@/utils'
import { Version } from '@/types/version'

const { Text, Title, Paragraph } = Typography
const { TextArea } = Input

interface VersionDetailProps {
  version: Version
  isCurrentVersion?: boolean
  onRevert?: (version: Version) => void
  onDelete?: (versionId: string) => void
  onComment?: (versionId: string, comment: string) => void
  onClose?: () => void
  showActions?: boolean
  readOnly?: boolean
}

const VersionDetail: React.FC<VersionDetailProps> = ({
  version,
  isCurrentVersion = false,
  onRevert,
  onDelete,
  onComment,
  onClose,
  showActions = true,
  readOnly = true,
}) => {
  const [commentModalVisible, setCommentModalVisible] = useState(false)
  const [commentText, setCommentText] = useState(version.comment || '')
  const [isFullscreen, setIsFullscreen] = useState(false)

  // 复制版本内容
  const handleCopyContent = async () => {
    const success = await copyToClipboard(version.content)
    if (success) {
      message.success('版本内容已复制到剪贴板')
    } else {
      message.error('复制失败')
    }
  }

  // 下载版本内容
  const handleDownloadContent = () => {
    const blob = new Blob([version.content], { type: 'text/plain;charset=utf-8' })
    const filename = `script_v${version.version_number}_${version.created_at.split('T')[0]}.sql`
    downloadFile(blob, filename)
    message.success('版本内容已下载')
  }

  // 处理版本回滚
  const handleRevert = () => {
    if (isCurrentVersion) {
      message.warning('当前版本无需回滚')
      return
    }

    Modal.confirm({
      title: '确认回滚版本',
      content: (
        <div>
          <p>确定要回滚到版本 v{version.version_number} 吗？</p>
          <p style={{ color: '#ff4d4f' }}>
            注意：回滚操作将创建一个新版本，当前版本不会被删除。
          </p>
        </div>
      ),
      okText: '确认回滚',
      cancelText: '取消',
      onOk: () => onRevert?.(version),
    })
  }

  // 处理版本删除
  const handleDelete = () => {
    if (isCurrentVersion) {
      message.error('不能删除当前版本')
      return
    }

    Modal.confirm({
      title: '确认删除版本',
      content: `确定要删除版本 v${version.version_number} 吗？此操作不可恢复。`,
      okText: '删除',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => onDelete?.(version.id),
    })
  }

  // 保存备注
  const handleSaveComment = async () => {
    try {
      await onComment?.(version.id, commentText)
      message.success('备注已保存')
      setCommentModalVisible(false)
    } catch (error) {
      message.error('保存备注失败')
    }
  }

  // 获取版本状态标签
  const getVersionStatusTag = () => {
    if (isCurrentVersion) {
      return <Tag color="blue">当前版本</Tag>
    }
    if (version.is_major) {
      return <Tag color="gold">主要版本</Tag>
    }
    return <Tag color="default">历史版本</Tag>
  }

  // 计算内容统计
  const getContentStats = () => {
    const lines = version.content.split('\n').length
    const chars = version.content.length
    const size = formatFileSize(new Blob([version.content]).size)
    
    return { lines, chars, size }
  }

  const stats = getContentStats()
  const cardStyle = isFullscreen ? {
    position: 'fixed' as const,
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    zIndex: 1000,
    margin: 0,
    borderRadius: 0,
  } : {}

  return (
    <Card 
      style={cardStyle}
      bodyStyle={{ 
        padding: 0,
        height: isFullscreen ? '100vh' : 'auto',
        display: 'flex',
        flexDirection: 'column',
      }}
    >
      {/* 版本头部信息 */}
      <div style={{ 
        padding: '16px 24px',
        borderBottom: '1px solid #f0f0f0',
        background: '#fafafa',
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
          <div>
            <Space size="middle" align="start">
              <div>
                <Space>
                  <FileTextOutlined style={{ fontSize: 20, color: '#1890ff' }} />
                  <Title level={4} style={{ margin: 0 }}>
                    版本 v{version.version_number}
                  </Title>
                  {getVersionStatusTag()}
                </Space>
                
                <div style={{ marginTop: 8 }}>
                  <Space size="large">
                    <Space size="small">
                      <UserOutlined style={{ color: '#666' }} />
                      <Text type="secondary">{version.created_by}</Text>
                    </Space>
                    <Space size="small">
                      <ClockCircleOutlined style={{ color: '#666' }} />
                      <Text type="secondary">{formatDateTime(version.created_at)}</Text>
                    </Space>
                  </Space>
                </div>
              </div>
            </Space>
          </div>

          {showActions && (
            <Space>
              <Tooltip title="复制内容">
                <Button
                  icon={<CopyOutlined />}
                  onClick={handleCopyContent}
                />
              </Tooltip>

              <Tooltip title="下载内容">
                <Button
                  icon={<DownloadOutlined />}
                  onClick={handleDownloadContent}
                />
              </Tooltip>

              <Tooltip title="编辑备注">
                <Button
                  icon={<EditOutlined />}
                  onClick={() => setCommentModalVisible(true)}
                />
              </Tooltip>

              {!isCurrentVersion && (
                <Tooltip title="回滚到此版本">
                  <Button
                    type="primary"
                    icon={<RollbackOutlined />}
                    onClick={handleRevert}
                  >
                    回滚
                  </Button>
                </Tooltip>
              )}

              {!isCurrentVersion && (
                <Tooltip title="删除版本">
                  <Button
                    danger
                    icon={<DeleteOutlined />}
                    onClick={handleDelete}
                  />
                </Tooltip>
              )}

              <Button onClick={onClose}>关闭</Button>
            </Space>
          )}
        </div>

        {/* 版本备注 */}
        {version.comment && (
          <div style={{ 
            marginTop: 12,
            padding: 12,
            background: '#fff',
            borderRadius: 6,
            border: '1px solid #e8e8e8',
          }}>
            <Space>
              <TagOutlined style={{ color: '#666' }} />
              <Text style={{ fontStyle: 'italic' }}>{version.comment}</Text>
            </Space>
          </div>
        )}
      </div>

      {/* 版本详细信息 */}
      <div style={{ padding: '16px 24px', borderBottom: '1px solid #f0f0f0' }}>
        <Descriptions size="small" column={4}>
          <Descriptions.Item label="版本号">
            v{version.version_number}
          </Descriptions.Item>
          <Descriptions.Item label="创建时间">
            {formatDateTime(version.created_at)}
          </Descriptions.Item>
          <Descriptions.Item label="创建者">
            {version.created_by}
          </Descriptions.Item>
          <Descriptions.Item label="版本类型">
            {version.is_major ? '主要版本' : '次要版本'}
          </Descriptions.Item>
          <Descriptions.Item label="内容行数">
            {stats.lines} 行
          </Descriptions.Item>
          <Descriptions.Item label="字符数">
            {stats.chars.toLocaleString()} 字符
          </Descriptions.Item>
          <Descriptions.Item label="文件大小">
            {stats.size}
          </Descriptions.Item>
          <Descriptions.Item label="变更摘要">
            {version.changes_summary || '无'}
          </Descriptions.Item>
        </Descriptions>
      </div>

      {/* 版本内容 */}
      <div style={{ flex: 1, minHeight: 400 }}>
        <MonacoSQLEditor
          value={version.content}
          height="100%"
          readOnly={readOnly}
          showMinimap={true}
          lineNumbers="on"
          folding={true}
          wordWrap="on"
        />
      </div>

      {/* 备注编辑模态框 */}
      <Modal
        title="编辑版本备注"
        open={commentModalVisible}
        onOk={handleSaveComment}
        onCancel={() => {
          setCommentModalVisible(false)
          setCommentText(version.comment || '')
        }}
        okText="保存"
        cancelText="取消"
        width={600}
      >
        <div>
          <div style={{ marginBottom: 16 }}>
            <Text strong>版本: </Text>
            <Text>v{version.version_number}</Text>
            <Text type="secondary" style={{ marginLeft: 16 }}>
              {formatDateTime(version.created_at)}
            </Text>
          </div>
          
          <TextArea
            value={commentText}
            onChange={(e) => setCommentText(e.target.value)}
            placeholder="输入版本备注..."
            rows={4}
            maxLength={500}
            showCount
          />
          
          <div style={{ marginTop: 8, color: '#666', fontSize: 12 }}>
            版本备注将帮助您和团队成员了解此版本的主要变更内容。
          </div>
        </div>
      </Modal>
    </Card>
  )
}

export default VersionDetail